﻿using Application.Cache;
using Domain.Event;
using Domain.IRepositorys;
using Domain.Services;
using Infrastructure.Job;
using Infrastructure.UniOfWorkBase;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utility;
using static Utility.PolicyUtil;

namespace Application.Job
{
    [Job("0 0/10 * * * ? ")]
    public class TaskOutTimeJob : AbstractJob
    {
        public TaskService taskService { get; set; }
        public ITaskRepository taskRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public TaskDetailsCache taskDetailsCache { get; set; }

        public ILogger<TaskOutTimeJob> Logger { get; set; }
        public override void Run()
        {
            var status = new[] { Domain.Types.TaskStatus.进行中, Domain.Types.TaskStatus.暂停 };
            var list = taskRepository.Entities.Where(i => status.Contains(i.Status) && !i.IsFinishAll && i.FinishTime >= DateTime.Now).ToList();

            foreach (var item in list)
            {
                PolicyUtil.Retry<bool>(2, () =>
                {
                    //item.Status = Domain.Types.TaskStatus.任务待完成;
                    taskDetailsCache.RemoveCache(item.ID);
                    taskService.DoTaskClose(item, Domain.Types.TaskStatus.任务完成);

                    try
                    {
                        efUnitOfWork.Commit();
                        //efUnitOfWork.Reset();
                    }
                    catch (DbUpdateConcurrencyException ex)
                    {
                        throw new PolicyRetryException();
                    }
                    catch (Exception ex)
                    {
                        Logger.LogException(ex);
                        return false;
                    }

                    return true;
                });
            }

        }
    }
}
